from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from .config import Config
import logging
from logging.handlers import RotatingFileHandler
import os

db = SQLAlchemy()
login_manager = LoginManager()
login_manager.login_view = 'auth.login'

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    db.init_app(app)
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(id):
        from .models import User
        return User.query.get(int(id))

    # 配置日志
    if not app.debug:
        if not os.path.exists(app.config['LOG_PATH']):
            os.makedirs(app.config['LOG_PATH'])
        file_handler = RotatingFileHandler(
            os.path.join(app.config['LOG_PATH'], 'app.log'),
            maxBytes=10240,
            backupCount=10
        )
        file_handler.setFormatter(logging.Formatter(
            '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
        ))
        file_handler.setLevel(logging.INFO)
        app.logger.addHandler(file_handler)
        app.logger.setLevel(logging.INFO)
        app.logger.info('Application startup')

    # 注册蓝图
    from .routes import auth, main
    app.register_blueprint(auth.bp)
    app.register_blueprint(main.bp)

    # 只在首次运行时创建表
    with app.app_context():
        db.create_all()
        app.logger.info('Checked database tables')

    # 添加自定义过滤器
    @app.template_filter('project_type_text')
    def project_type_text(project_type):
        types = {
            'industrial': '工业测控',
            'environmental': '环境监测'
        }
        return types.get(project_type, '未知类型')
    
    @app.template_filter('status_text')
    def status_text(status):
        statuses = {
            'draft': '草稿',
            'pending': '待审核',
            'approved': '已批准',
            'rejected': '已拒绝'
        }
        return statuses.get(status, '未知状态')
    
    @app.template_filter('status_color')
    def status_color(status):
        colors = {
            'draft': 'secondary',
            'pending': 'warning',
            'approved': 'success',
            'rejected': 'danger'
        }
        return colors.get(status, 'secondary')

    return app 